package com.example.demo;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * Created by lilongfei on 2017/9/14.
 */
@Component
@Slf4j
public class BeanMessageListener {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public void receiveMessage(Map<String, Object> message) throws Exception {
    log.info("Received <" + message + ">");
    Assert.isTrue(message.containsKey("table"),"have no table denfine");
    Object table = message.get("table");
    Assert.notNull(table,"have no table denfine");
    message.remove("table");
    List<String> columns =  new ArrayList<>(message.keySet());
    int i = jdbcTemplate.update(createSql(table.toString(),columns)
        ,statement->setStatement(statement,message,columns));
    Assert.isTrue(i == 1,"save to db error,message");
  }

  private String createSql(String table,List<String> columns){
    StringBuilder builder = new StringBuilder();
    builder.append(" insert into ").append(table).append(" (");
    columns.forEach(s -> builder.append(s).append(","));
    builder.delete(builder.length()-1,builder.length());
    builder.append(") values (");
    columns.forEach(s -> builder.append("?,"));
    builder.delete(builder.length()-1,builder.length());
    builder.append(" ) ");
    log.info("create sql : {}",builder.toString());
    return builder.toString();
  }

  private void setStatement(PreparedStatement ps,Map<String,Object> map,List<String> columns)
      throws SQLException {
    int index = 1;
    for(String column : columns){
      ps.setObject(index,map.get(column));
      index++;
    }
  }
}
